package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.lang.Assert;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    private static long expiration = 30 * 60 * 1000; //30min
    private static String secretString = "eN8bKZQxXvga5a1T63Kri7rNIekgBvBK2XSWmBkqNAU";
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64URL.decode(secretString));//通过Key类提供的hmacShaKeyFor函数生成,这个函数的参数是一个数组
    //所以先通过 Decoders 类提供的函数将secretString通过Base64URL算法解码为字节数组

    //生成令牌
    public static String genJWT(Map<String,Object> claims)
    {
         String compact = Jwts.builder()
                .setClaims(claims)
                .signWith(key) //设置签名,传密码进去
                .setExpiration(new Date(System.currentTimeMillis() + expiration)) //设置过期时间
                .compact();

        return compact;
    }


    //校验令牌
    public static Claims verify(String token)
    {
        //String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJpZCI6NX0.Wvg0JnilJO--Rxeklz2bpVpWHYnpfeJcoXV9df8pU4w";
        JwtParser build =  Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch(ExpiredJwtException e) {
            System.out.println("token过期,检验失败,token:"+token);
        }catch(SignatureException e) {
            System.out.println("token签名不符合");
        }catch(Exception e) {
            System.out.println("token不正确,校验失败,token:" + token);
        }

        return claims;
    }

    public static Integer getUserIdFromToken(String token)
    {
        Claims claims = verify(token);
//        if(claims == null)
//        {
//            return null;
//        }
        Assert.notNull(claims,"token不合法");
        Integer userId = (Integer)claims.get("id");
        return userId;
    }

}
